﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Drawing.Drawing2D;


namespace PDFMerge
{
    /// <summary>
    /// Form responsible for handling images and converting them to 8.5 x 11 PDF docs 
    /// </summary>
    public partial class ImportImage : Form
    {
        public System.Drawing.Image importPic { get; set; } //Stores the image
        public String pdfDoc { get; set; } //Stores the filePath
        public String PDFName { get; set; } //Stores friendly name if wanted

        /// <summary>
        /// Constructor that takes in an image for the form to be displayed
        /// </summary>
        /// <param name="import">Image to convert to PDF and show on screen</param>
        public ImportImage(System.Drawing.Image import)
        {
            InitializeComponent();
            
            //Initialize the public variable
            importPic = import;

            //Get the thumb nail size
            pictureBox.Image = getThumb();

            //Is this inches?
            this.label_width.Text = Math.Round((importPic.Width / importPic.HorizontalResolution),2).ToString();
            this.label_height.Text = Math.Round((importPic.Height / importPic.VerticalResolution),2).ToString();
                
        }

        /// <summary>
        /// Gets a thumbnail (reduced quality) of the picture and sizes it to the picture box
        /// </summary>
        /// <returns>Image: thumbnail</returns>
        public System.Drawing.Image getThumb()
        {
            System.Drawing.Image thumb = importPic.GetThumbnailImage(
               pictureBox.Width,
               pictureBox.Height,
               null,
               IntPtr.Zero);
            return thumb;
        }
        
        /// <summary>
        /// Rotates the original image 90-degress clockwise, and fetches a thumbnail version of that
        /// </summary>
        private void rotateRight()
        {
            importPic.RotateFlip(RotateFlipType.Rotate90FlipNone);
            this.pictureBox.Image = getThumb();
            this.pictureBox.Refresh();

            this.label_width.Text = Math.Round((importPic.Width / importPic.HorizontalResolution),2).ToString();
            this.label_height.Text = Math.Round((importPic.Height / importPic.VerticalResolution),2).ToString();
            this.label_height.Refresh();
            this.label_width.Refresh();

        }
        
        /// <summary>
        /// Resizes the picture to fit 8.5 width x 11 height
        /// Note: I have no idea why we have to divide the resolution by 3.125 ??
        /// </summary>
        /// <returns>Image: resized to 8.5x11</returns>
        private System.Drawing.Image resizeToLetterHead()
        {
            // 8.5 width X DPI 2550
           // 11 height X DPI = 3300

            int _width = (int)Math.Round(8.5 * (importPic.HorizontalResolution / 3.125));
            int _height = (int)Math.Round(11 * (importPic.VerticalResolution / 3.125));

            Bitmap newImage = new Bitmap(_width, _height);
            using (Graphics gr = Graphics.FromImage(newImage))
            {
                gr.SmoothingMode = SmoothingMode.HighQuality;
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.DrawImage(importPic, new System.Drawing.Rectangle(0, 0, _width, _height));
            }
            return newImage;
        }
        
        /// <summary>
        /// Makes a PDF document (on file system) 8.5x11 and adds the current state of importPic to it
        /// Note: GUID was used to generate unique file names
        /// </summary>
        private void makePdf()
        {
            Document doc = new Document(PageSize.LETTER,0,0,0,0);
            try
            {
                String newFilePath = System.IO.Path.GetTempPath() + Guid.NewGuid() + "_temp.pdf";
               PdfWriter writer = PdfWriter.GetInstance(doc, new System.IO.FileStream(
                   newFilePath,
                   System.IO.FileMode.Create));
                doc.Open();
                iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(importPic, System.Drawing.Imaging.ImageFormat.Jpeg);
                pic.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
                doc.Add(pic);
                doc.Close();

                //Store it into the public form
                pdfDoc = newFilePath;
                if (!(String.IsNullOrEmpty(this.txt_Name.Text)))
                {
                    PDFName = this.txt_Name.Text;
                }
                
            }
            catch (Exception ex)
            { 
              //Lets pray we never get here, otherwise something is really wrong :(
                MessageBox.Show(
                    String.Format("There was a problem converting the document/image to PDF :(\r\nReason: {0}", ex.Message),
                    "Error!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                this.Close();
            }
        }
        
        /// <summary>
        /// Handles the Rotate button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Rotate_Click(object sender, EventArgs e)
        {
            this.rotateRight();
        }

        /// <summary>
        /// Handles the Import button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Import_Click(object sender, EventArgs e)
        {
            makePdf();
        }

        /// <summary>
        /// Event is used to give the Name text box focus when the form loads
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImportImage_Shown(object sender, EventArgs e)
        {
            this.txt_Name.Focus();
        }
        
    }
}
